package Jasper.servlet;

import Jasper.entity.Page;
import Jasper.entity.Product;
import Jasper.entity.Type;
import Jasper.entity.User;
import Jasper.service.IUserService;
import Jasper.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName UserServlet
 * @Author jiangjiajia
 * @JDK-Version 1.8
 * @Date 2021/5/22 11:41 am
 * @Version 1.0
 * @Description 必须描述类的业务用途
 **/
@WebServlet("/UserServlet")

/**
 * 注册功能
 */
public class UserServlet extends BaseServlet {
    private IUserService userService = new UserServiceImpl();

    //工厂模式
    public Type register(HttpServletRequest request, HttpServletResponse response) throws FileUploadException, IOException, InvocationTargetException, IllegalAccessException, ServletException, InvocationTargetException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> list = upload.parseRequest(request);
        User user = new User();
        HashMap<String, String> map = new HashMap<>();
        for (FileItem fileItem : list) {
            //判断是否为非文本信息
            if (!fileItem.isFormField()) {
                InputStream is = fileItem.getInputStream();
                String path = getServletContext().getRealPath("img");
                File file = new File(path);
                if (!file.exists()) {
                    file.mkdirs();
                }
                //改变文件名
                String fileName = fileItem.getName();
                UUID uuid = UUID.randomUUID();
                fileName = uuid.toString() + "_" + fileName;

                FileOutputStream fos = new FileOutputStream(new File(path, fileName));
                IOUtils.copy(is, fos);
                is.close();
                fos.close();
                //存储图片的名字
                user.setImgUrl(fileName);
            } else {
                //userName  --  hobbies -- hobbies
                String value = map.get(fileItem.getFieldName());
                if (value == null) {
                    //userName:中文   hobbies:eat
                    map.put(fileItem.getFieldName(), fileItem.getString("utf-8"));
                } else {
                    //hobbies:eat,drink
                    map.put(fileItem.getFieldName(), value + "," + fileItem.getString("utf-8"));
                }
            }
        }
        //eat,drink
        String hobbiesString = map.get("hobbies");
        String[] hobbies = hobbiesString.split(",");
        user.setHobbies(hobbies);
        user.setHobbiesString(hobbiesString);
        //会自动把map中的value赋值给user对象，前提条件是map的key跟user对象的属性相同
        BeanUtils.populate(user, map);
        Type type = userService.addUser(user);
        //把对象成功存放到数据库中
        System.out.println(user);
//        Type type = new Type("success");
        //响应前端
        return type;
    }

    /**
     * 用户校验功能和登录功能
     */


//返回 Type类型
    private Type login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");

        //2.校验用户名和密码
        //在 session 中存储用户登录凭证(id)
        Type type = userService.checkUser(request, response, username, password, remember);
        return type;
    }

    /**
     * 校验用户名是否重复
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void checkUsername(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.获取前端数据
        String username = request.getParameter("username");
        //2.校验 username 是否重复
        String str = userService.checkUsername(username);
        //3.响应客户端
        response.getWriter().write(str);
    }

    /**
     * 获取产品分页
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    private void togetPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取当前页
        String currentPage = request.getParameter("currentPage");
        //2.业务处理      --  获取page对象
        Page page = userService.getPage(Integer.parseInt(currentPage));
        //3.响应客户端 响应客户端
        request.setAttribute("page", page);
        request.getRequestDispatcher("userList.jsp").forward(request, response);
    }

    /**
     * 新增商品上架功能
     *
     * @param request
     * @param response
     * @return
     * @throws FileUploadException
     * @throws IOException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws ServletException
     * @throws InvocationTargetException
     */

    //工厂模式
    public Type addProduct(HttpServletRequest request, HttpServletResponse response) throws FileUploadException, IOException, InvocationTargetException, IllegalAccessException, ServletException, InvocationTargetException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> list = upload.parseRequest(request);
        Product product = new Product();
        HashMap<String, String> map = new HashMap<>();
        for (FileItem fileItem : list) {
            //判断是否为非文本信息
            if (!fileItem.isFormField()) {
                InputStream is = fileItem.getInputStream();
                String path = getServletContext().getRealPath("img");
                File file = new File(path);
                if (!file.exists()) {
                    file.mkdirs();
                }
                //改变文件名
                String fileName = fileItem.getName();
                UUID uuid = UUID.randomUUID();
                fileName = uuid.toString() + "_" + fileName;

                FileOutputStream fos = new FileOutputStream(new File(path, fileName));
                IOUtils.copy(is, fos);
                is.close();
                fos.close();
                //存储图片的名字
                product.setImgUrl(fileName);
            } else {
                //userName  --  hobbies -- hobbies
                String value = map.get(fileItem.getFieldName());
                if (value == null) {
                    //userName:中文   hobbies:eat
                    map.put(fileItem.getFieldName(), fileItem.getString("utf-8"));
                } else {
                    //hobbies:eat,drink
                    map.put(fileItem.getFieldName(), value + "," + fileItem.getString("utf-8"));
                }
            }
        }
/*        //eat,drink
        String hobbiesString = map.get("hobbies");
        String[] hobbies = hobbiesString.split(",");
        product.setHobbies(hobbies);
        user.setHobbiesString(hobbiesString);*/

        //会自动把map中的value赋值给user对象，前提条件是map的key跟user对象的属性相同
        BeanUtils.populate(product, map);
        Type type = userService.addProducr(product);
        //把对象成功存放到数据库中
        System.out.println(product);
//        Type type = new Type("success");
        //响应前端
        return type;
    }
}